import { electronAPI } from '@electron-toolkit/preload'
import { contextBridge, ipcRenderer } from 'electron'
import { IPCEvent } from '@common/constant'

// Custom APIs for renderer
const api = {
  shortcut: (shortcut: string) => {
    return ipcRenderer.invoke(IPCEvent.SHORTCUT, shortcut)
  },
  setIgnoreMouseEvents: (ignore: boolean, options?: { forward: boolean }) => {
    ipcRenderer.send(IPCEvent.IGNORE_MOUSE_EVENT, ignore, options)
  },
  openConfigWindow: () => {
    ipcRenderer.send(IPCEvent.OPEN_CONFIG_WINDOW)
  },
  sql: (sql: string, type: SqlActionType, params = {}) => {
    return ipcRenderer.invoke(IPCEvent.SQL, sql, type, params)
  },
  openWindow: (name: WindowNameType) => {
    ipcRenderer.send(IPCEvent.OPEN_WINDOW, name)
  },
  closeWindow: (name: WindowNameType) => {
    ipcRenderer.send(IPCEvent.CLOSE_WINDOW, name)
  },
  selectDatabaseDirectory: () => {
    return ipcRenderer.invoke(IPCEvent.SELECT_DATABASE)
  },
  setDatabaseDirectory: (path: string) => {
    return ipcRenderer.send(IPCEvent.SET_DATABASE_DIRECTORY, path)
  },
  initTable: () => {
    ipcRenderer.send(IPCEvent.INIT_TABLE)
  }
}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  // @ts-ignore (define in dts)
  window.electron = electronAPI
  // @ts-ignore (define in dts)
  window.api = api
}
